/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities;

import scores.HibernateUtil;
import java.util.ArrayList;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author ALIEN
 */
public class League {
    private long id;
    private String name;
    private Discipline discipline;
    private Session session;
    private SelectItem[] leagues;


    /**
     * @return the id
     */
    public long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(long id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public String dodaj() {
        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            session.save(this);
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return "ok";
    }

    /**
     * @return the discipline
     */
    public Discipline getDiscipline() {
        return discipline;
    }

    /**
     * @param discipline the discipline to set
     */
    public void setDiscipline(Discipline discipline) {
        this.discipline = discipline;
    }

    public SelectItem[] getLeagues() {
        ArrayList leagueList = new ArrayList();

        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from League");
            leagueList = (ArrayList) q.list();
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }

        leagues = new SelectItem[leagueList.size()];
        for (int i = 0; i < leagueList.size(); i++) {
            leagues[i] = new SelectItem(leagueList.get(i), ((League) (leagueList.get(i))).name);
        }
        return leagues;
    }

    @Override
    public boolean equals(Object obj) {
        return true;
    }


    public void actionLsnr(ActionEvent e) {
        id = (Long)(e.getComponent().getAttributes().get("id"));
        System.out.println(id);
        System.out.println(id);
        System.out.println(id);
        System.out.println(id);
        System.out.println(id);
    }
}
